# -*- coding: utf-8 -*-
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings")
get_wsgi_application()

import settings
import tornado.escape
import tornado.ioloop
import tornado.web
from urls import urls
import logging
from backend.models import BMSUser

def utf8(value):
    """Converts a string argument to a byte string.

    If the argument is already a byte string or None, it is returned unchanged.
    Otherwise it must be a unicode string and is encoded as utf8.
    """
    if value is None or value == 'None':
        value = ""
    if isinstance(value, tornado.escape._UTF8_TYPES):
        return value
    if not isinstance(value, unicode_type):
        raise TypeError(
            "Expected bytes, unicode, or None; got %r" % type(value)
        )
    return value.encode("utf-8")
tornado.escape.utf8 = utf8


LOG_FORMAT = ('%(levelname) -10s %(asctime)s %(name) -30s %(funcName) '
              '-35s %(lineno) -5d: %(message)s')
LOGGER = logging.getLogger(__name__)


def ping_db():
    BMSUser.objects.filter(id=1).first()


def main():
    address, port, env = settings.ADDRESS, settings.PORT, settings.ENV
    db_ping_secs, tornado_env = settings.DB_PING_SECS, settings.TORNADO_ENV

    ioloop = tornado.ioloop.IOLoop.instance()
    application = tornado.web.Application(urls, **tornado_env)

    http_server = tornado.httpserver.HTTPServer(application, xheaders=True, max_buffer_size=500000000, max_body_size=500000000)
    http_server.listen(port, address)
    print('huanxi cms server run on {}({}:{})'.format(env, address, port))

    tornado.ioloop.PeriodicCallback(ping_db, int(db_ping_secs * 1000)).start()
    try:
        ioloop.start()
    except KeyboardInterrupt:
        ioloop.stop()


if __name__ == '__main__':
    main()

